angular.module("cart",[])
.factory("cart",function(){
    var cartData=[];
    return{
        addProduct:function(id,name,price){
            var addedToExistingItem=false;
            for(var i=0;i<cartData.length;i++){
                if(cartData[i].id==id){
                    cartData[i].count++;
                    addedToExistingItem=true;
                    break;
                }
            }
            if(!addedToExistingItem){
                cartData.push({
                    count:1,id:id,price:price,name:name
                });
            }
        },
        reomveProduct:function(id){
            for(var i=0;i<cartData.length;i++){
                if(cartData[i].id==id){
                    cartData.splice(i,1);
                    break;
                }
            }
        },
        getProducts:function(){
            return cartData;
        }
    }
})
.directive("cartb",function(cart){
    return{
        restrict:"AE",
        templateUrl:"views/cartSummary.html",
        controller:function($scope){
            var cartData=cart.getProducts();
            //计算单品总价
            $scope.total=function(){
                var total=0;
                for(var i=0;i<cartData.length;i++){
                    total+=(cartData[i].price*cartData[i].count);
                }
                return total;
            }
            //计算总价
            $scope.itemCount=function(){
                var total=0;
                for(var i=0;i<cartData.length;i++){
                    total+=cartData[i].count;
                }
                return total;
            }
        }
    }
})